const actions = {

}

const mutations = {
  // 添加新的商品进购物车
  ADDGOODS(state,data){
    let goodsList = state.cartList.goodsList
    // 表示该商品是否已经加入过购物车：默认值true,表示未加入购物车
    let isNew = true
    // 给每个商品添加一个是否选中的字段：默认值为false
    data.isChecked = false
    goodsList.forEach(v => {
      if(v.id == data.id){
        v.goodsNum += 1
        isNew = false
      }
    })
    isNew && goodsList.push(data)
  },
  //  手动设置商品数量,点击 + 或者 -
   SETNUMBER(state,data){
    let goodsList = state.cartList.goodsList
    const tag = data.tag
    goodsList.forEach(v => {
      if(v.id== data.id){
        switch(tag){
          case '+':
            v.goodsNum += 1
            break
          case '-':
            if(v.goodsNum == 1){
              break
            }
            v.goodsNum -= 1
            break
          case '#':
            if(data.num <= 0){
              v.goodsNum = v.goodsNum +1
              break
            }
            v.goodsNum = data.num
        }
      }
    })
   },
   SETSTATUS(state,{id,status}){
    let goodsList = state.cartList.goodsList
    goodsList.forEach(v => {
      if(v.id == id){
        v.isChecked = status
      }
    })

   },
   SETALLSTATUS(state,status){
    let goodsList = state.cartList.goodsList
    goodsList.forEach(v=>{
      v.isChecked = status
    })
   },
   DELETE(state){
    let goodsList = state.cartList.goodsList
    state.cartList.goodsList = goodsList.filter(v=>!v.isChecked)
   }
}

const state = {
  cartList:{
    userId:localStorage.getItem('status'),
    goodsList:[]
  }
}

const getters = {
  goodsList(state){
    return state.cartList.goodsList
  },
  userId(state){
    return state.cartList.userId
  }
}

export default {
  namespaced:true,
  state,
  actions,
  mutations,
  getters
}